package com.liwy3.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * Copyright © 元气森林（北京）食品科技集团有限公司. All rights reserved.
 *
 * @Description:
 * @author: Crazy4J
 * @date: 2021年12月27日 11:01
 * @version: V1.0
 */
@Slf4j
public class ChartServer {

    private String serverAddress;
    private int port;

    public ChartServer(String serverAddress, int port) {
        this.serverAddress = serverAddress;
        this.port = port;
    }


    private final static String SERVER_ADDRESS = "127.0.0.1";
    private final static int PORT = 7777;
    private static volatile boolean flag = false;

    public static void main(String[] args) throws InterruptedException {

        ChartServer chartServer = new ChartServer(SERVER_ADDRESS, PORT);
        chartServer.start();

    }

    public void start() throws InterruptedException {

        Thread chartServerThread = new Thread(() -> {
            try {
                EventLoopGroup bossGroup = new NioEventLoopGroup();
                EventLoopGroup workerGroup = new NioEventLoopGroup();
                ServerBootstrap bootstrap = new ServerBootstrap();
                bootstrap.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel channel) throws Exception {
                                channel.pipeline()
                                        .addLast(new IdleStateHandler(0, 0, 30 * 3, TimeUnit.SECONDS))  // beat 3N, close if idle
//                                        .addLast(new HttpServerCodec())
//                                        .addLast(new HttpObjectAggregator(5 * 1024 * 1024))  // merge request & reponse to FULL
                                        .addLast(new ChartServerHandler());
                            }
                        })
                        .childOption(ChannelOption.SO_KEEPALIVE, true);

                // bind
                ChannelFuture future = bootstrap.bind(port).sync();
                future.channel().closeFuture().sync();
            } catch (Exception e) {
                log.error("服务器异常:", e);
            }

        });
        chartServerThread.setDaemon(true);
        chartServerThread.start();
        Thread.sleep(1000);
    }

    static class ChartServerHandler extends ChannelInboundHandlerAdapter  {


        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

            //耗时较长的操作放入堆列中处理
            ctx.channel().eventLoop().execute(()->{
                try {
                    Thread.sleep(3000);
                    log.debug("耗时操作3S.....");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ByteBuf byteBuf = (ByteBuf) msg;
                System.out.println("收到客户端" + ctx.channel().remoteAddress() + "发送的消息：" + byteBuf.toString(CharsetUtil.UTF_8));
            });
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            //发送消息给客户端
            ctx.writeAndFlush(Unpooled.copiedBuffer("服务端已收到消息，并给你发送一个问号?", CharsetUtil.UTF_8));
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            //发生异常，关闭通道
            ctx.close();
        }
    }
}
